package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;



/*
 * getParameter() request.getParameter方法来获取表单参数的值
 * getParameterValues 参数出现一次以上 则调用此方法 并返回多个值
 * getParameterNames 获取请求中的所有参数的完整列表
 *
 * */

/*
 * Cookie是存储在客户端计算机上的文本文件。保留了各种跟踪信息。
 * 识别返回用户的部署
 *       服务器脚本向浏览器发送一组Cookie
 *       浏览器将这些信息存储在本地计算机上，
 *       当下一次浏览器向Web服务器发送任何请求 浏览器会把这些Cookie信息发送到服务器，服务器将使用这些信息来识别用户
 * Servlet Cookie处理需要对中文进行编码和解码
 *   String str=java.net.URLEncoder.encode()
 *   String str=java.net.URLEncoder.decode()
 *
 * */

@WebServlet("/HelloForm")
public class HelloForm extends HttpServlet {
    private static final long serialVersionUID = 1l;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Cookie nameCookie = new Cookie("name", URLEncoder.encode(req.getParameter("name"), "UTF-8"));
        Cookie urlCookie = new Cookie("url", URLEncoder.encode(req.getParameter("url"), "UTF-8"));

        nameCookie.setMaxAge(60*60*24);
        urlCookie.setMaxAge(60*60*24);

        resp.addCookie(nameCookie);
        resp.addCookie(urlCookie);


        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String title = "使用GET方法读取表单数据";
        String name = new String(req.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
//        out.println(req.getParameterNames());
        Enumeration enumeration = req.getParameterNames();
        while (enumeration.hasMoreElements()) {
            out.println("------------------->" + enumeration.nextElement() + "  \n ");
        }
        out.println(title);
        out.println(name);


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
